package yunquan.wang.modules.base.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import yunquan.wang.base.dao.DaoUtils;
import yunquan.wang.modules.base.dao.CodeValueDao;
import yunquan.wang.modules.base.entity.CodeType;
import yunquan.wang.modules.base.entity.CodeValue;
import yunquan.wang.modules.base.service.AppCodeService;

@Service("appCodeService")
@Transactional(value = "jpaTransaction")
public class AppCodeServiceImpl extends CodeTypeServiceImpl  implements AppCodeService {

	private static Map<String, Set<CodeValue>> codeCache = new HashMap<String, Set<CodeValue>>();
 
	@Resource
	private CodeValueDao codeValueDao;

	@Override
	public Set<CodeValue> getAllCodeValue(String type) {
		
		Set<CodeValue> typeCode=	codeCache.get(type);
		if(typeCode==null){
		CodeType codeType =getDao().findOne(Specifications
				.where(DaoUtils.eq("type", type)));
		  String valueType=codeType.getValueType();
	 Class clazz=null;
	try {
		clazz = Class.forName(valueType);
	} catch (ClassNotFoundException e) {
		e.printStackTrace();
	}
		Set<CodeValue> codeValues = codeType.getCodeValues();
		for (CodeValue value : codeValues) {
			String valueString = value.getStringValue();
			if (clazz.getSimpleName().equals(valueType)) {
				value.setValue(valueString);
			} else {
				value.setValue(ConvertUtils.convert(valueString, clazz));
			}
		}
		codeCache.put(type, codeValues);
		return codeValues;
		}
		//ConvertUtils
		return typeCode;
	}

	@Override
	public Object getCodeValue(String type, String code) {
		Set<CodeValue> typeCode=	getAllCodeValue(type);
		for(CodeValue single:typeCode)
		{
			if(single.getCode().equalsIgnoreCase(code));
			{
				return single.getValue();
			}
		}
		return null;
	}

	@Override
	public CodeValue saveCodeValue(CodeValue entity) {
		// TODO Auto-generated method stub
		return codeValueDao.save(entity);
	}

	@Override
	public void deleteCodeValue(String id) {
		codeValueDao.delete(id);
		
	}

	@Override
	public CodeValue getCodeValue(String id) {
		// TODO Auto-generated method stub
		return codeValueDao.findOne(id);
	}

	@Override
	public List<CodeValue> getCodeValues(String id) {
		return codeValueDao.findAll(Specifications
				.where(DaoUtils.eq("codeType.id", id)));
	}
 

}
